/**
 * @author
 * @description 路由守卫，目前两种模式：all模式与intelligence模式
 */
import router from '@/router'
import store from '@/store'
import VabProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/pageTitle'
import {
  authentication,
  loginInterception,
  progressBar,
  recordRoute,
  routesWhiteList,
} from '@/config'
import { getRouterList } from '@/api/router'

VabProgress.configure({
  easing: 'ease',
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
})
router.beforeResolve(async (to, from, next) => {
  if (progressBar) VabProgress.start()
  let hasToken = store.getters['user/accessToken']
  //if (!loginInterception) hasToken = true
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      if (progressBar) VabProgress.done()
    } else {
      const hasRoles =
        store.getters['user/roles'] && store.getters['user/roles'].length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          //拿到 当前用的路由详细信息
          let userInfo
          if (!loginInterception) {
            //settings.js loginInterception为false时，创建虚拟权限
            //此处有点问题 todo
            await store.dispatch('user/setRoles', ['admin'])
            userInfo = ['admin']
          } else {
            userInfo = await store.dispatch('user/getUserInfo')
          }
          //如果 没有角色就跳转到401 todo userInfo[roles]
          if (userInfo == 'noroles') {
            next('/401')
            if (progressBar) VabProgress.done()
            return
          }
          // 登录成功之后获取权限路由及按钮
          let accessRoutes = []
          //在此处将请求的路由和基本的路由进行处理
          if (authentication === 'intelligence') {
            accessRoutes = await store.dispatch('routes/setRoutes', userInfo)
          } else if (authentication === 'all') {
            let userData = await getRouterList()
            userData.data.routes[0].children[0].meta.affix = true
            await store.dispatch('user/setButtons', userData.data.buttons)
            accessRoutes = await store.dispatch(
              'routes/setAllRoutes',
              userData.data.routes
            )
          }
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch {
          await store.dispatch('user/resetAccessToken')
          next(`/login?redirect=${to.path}`)
          if (progressBar) VabProgress.done()
        }
      }
    }
  } else {
    if (routesWhiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      if (recordRoute) {
        next(`/login?redirect=${to.path}`)
      } else {
        next('/login')
      }

      if (progressBar) VabProgress.done()
    }
  }
  document.title = getPageTitle(to.meta.title)
})
router.afterEach(() => {
  if (progressBar) VabProgress.done()
})
